<template>
  <div style="padding: 20px;">
    <div class="searchDiv" style="padding-bottom: 20px;">
      <el-form ref="form" :model="query" label-width="70px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-input
              v-model="query.goodsId"
              size="mini"
              placeholder="请输入商品编号"
              style="width: 200px;"
              clearable
            />
            <el-button type="primary" icon="el-icon-search" style="margin-left: -5px;" @click="seek">查找</el-button>
            <el-button type="primary" icon="el-icon-edit" style="margin-left: 6px;" @click="add">添加</el-button>
            <el-button type="primary" icon="el-icon-download" style="margin-left: 6px;">导出</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="tables">
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column prop="id" label="团购规则ID" width="153" />
        <el-table-column prop="goodsId" label="商品ID" width="150" />
        <el-table-column prop="goodsName" label="名称" width="187" />
        <el-table-column prop="picUrl" label="图片" width="150">
          <template v-slot="scope">
            <img :src="scope.row.picUrl" alt="" style=" height: 40px; width: 40px;">
          </template>
        </el-table-column>
        <el-table-column prop="discount" label="团购优惠" width="150" />
        <el-table-column prop="discountMember" label="团购要求" width="150" />
        <el-table-column prop="status" label="状态" width="150">
          <template v-slot="scope">
            <el-tag v-if="scope.row.status == 0" type="success">正常</el-tag>
            <el-tag v-if="scope.row.status == 1">到期下线</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="expireTime" label="结束时间" width="150" />
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button size="mini" type="primary" @click="redact(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="deleteRule(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="paging">
      <pagination :total="total" :page="query.page" style="margin-top: 20px;" @size="setSize" @current="setCurrent" />
    </div>
    <div class="dialogDiv">
      <el-dialog :title="title" :visible.sync="dialogFormVisible">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" style="width: 400px;margin-left: 50px;">
          <el-form-item label="商品ID" label-width="120px" prop="goodsId">
            <el-input v-model="ruleForm.goodsId" style="width: 280px;" clearable />
          </el-form-item>
          <el-form-item label="团购折扣" label-width="120px" prop="discount">
            <el-input v-model="ruleForm.discount" style="width: 280px;" clearable />
          </el-form-item>
          <el-form-item label="团购人数要求" label-width="120px" prop="discountMember">
            <el-input v-model="ruleForm.discountMember" style="width: 280px;" clearable />
          </el-form-item>
          <el-form-item label="过期时间" label-width="120px" prop="expireTime">
            <el-date-picker v-model="ruleForm.expireTime" type="datetime" placeholder="选择日期" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="resetForm('ruleForm')">取 消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { listGroupon, deleteGroupon, editGroupon, publishGroupon } from '@/api/groupon'
import pagination from './pagination.vue'
export default {
  components: {
    pagination
  },
  data() {
    return {
      tableData: [],
      total: null,
      title: null,
      dialogFormVisible: false,
      query: {
        page: 1,
        limit: 20,
        goodsId: null
      },
      ruleForm: {
        goodsId: null,
        discountMember: null,
        discount: null,
        expireTime: null
      },
      row: {},
      rules: {
        goodsId: [
          { required: true, message: '商品不能为空', trigger: 'blur' }
        ],
        discountMember: [
          { required: true, message: '团购折扣不能为空', trigger: 'blur' }
        ],
        discount: [
          { required: true, message: '团购人数不能为空', trigger: 'blur' }
        ],
        expireTime: [
          { required: true, message: '过期时间不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 列表
    getList() {
      listGroupon(this.query).then(res => {
        if (res.data.errno == 0) {
          this.tableData = res.data.data.list
          this.total = res.data.data.total
        }
      })
    },
    // 分页
    setSize(val) {
      this.query.page = 1
      this.query.limit = val
      this.getList()
    },
    setCurrent(val) {
      this.query.page = val
      this.getList()
    },
    // 查找
    seek() {
      listGroupon(this.query).then(response => {
        this.tableData = response.data.data.list
        this.total = response.data.data.total
      })
    },
    // 添加
    add() {
      this.dialogFormVisible = true
      this.title = '创建'
      this.ruleForm.goodsId = null
      this.ruleForm.discountMember = null
      this.ruleForm.discount = null
      this.ruleForm.expireTime = null
      this.$nextTick(() => {
        this.$refs['ruleForm'].clearValidate()
      })
    },
    // 校验
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title == '创建') {
            // 确保 expireTime 是一个 Date 对象
            if (typeof this.ruleForm.expireTime === 'string') {
              this.ruleForm.expireTime = new Date(this.ruleForm.expireTime)
            }
            const formattedTime = this.ruleForm.expireTime.toISOString().slice(0, 19).replace('T', ' ')
            this.ruleForm.expireTime = formattedTime
            publishGroupon(this.ruleForm).then(res => {
              if (res.data.errno == 0) {
                this.dialogFormVisible = false
                this.$notify({
                  title: '成功',
                  message: `创建团购规则${res.data.errmsg}`,
                  type: 'success'
                })
                this.getList()
                this.$refs[formName].resetFields()
              }
            }).catch(err => {
              this.$notify.error({
                title: '失败',
                message: err.data.errmsg
              })
            })
          } else if (this.title == '编辑') {
            if (typeof this.ruleForm.expireTime === 'string') {
              this.ruleForm.expireTime = new Date(this.ruleForm.expireTime)
            }
            const formattedTime = this.ruleForm.expireTime.toISOString().slice(0, 19).replace('T', ' ')
            this.ruleForm.expireTime = formattedTime
            editGroupon({
              ...this.ruleForm,
              addTime: this.row.addTime,
              deleted: this.row.deleted,
              goodsName: this.row.goodsName,
              id: this.row.id,
              picUrl: this.row.picUrl,
              status: this.row.status,
              updateTime: this.row.updateTime
            }).then(res => {
              if (res.data.errno == 0) {
                this.dialogFormVisible = false
                this.$notify({
                  title: '成功',
                  message: `编辑团购规则${res.data.errmsg}`,
                  type: 'success'
                })
                this.getList()
                this.$refs[formName].resetFields()
              }
            }).catch(err => {
              this.$notify.error({
                title: '失败',
                message: err.data.errmsg
              })
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
      this.ruleForm.expireTime = null
      this.ruleForm.goodsId = null
      this.ruleForm.discountMember = null
      this.ruleForm.discount = null
    },
    // 删除
    deleteRule(row) {
      console.log(row)
      deleteGroupon(row).then(res => {
        if (res.data.errno == 0) {
          this.$notify({
            title: '成功',
            message: `删除团购规则${res.data.errmsg}`,
            type: 'success'
          })
          this.getList()
        }
      })
    },
    // 编辑
    redact(row) {
      this.dialogFormVisible = true
      this.title = '编辑'
      this.ruleForm.goodsId = row.goodsId
      this.ruleForm.discountMember = row.discountMember
      this.ruleForm.discount = row.discount
      this.ruleForm.expireTime = row.expireTime
      this.row = row
    }
  }
}
</script>

<style lang="scss" scoped>
  ::v-deep tr div {
    text-align: center !important;
  }
  .paging {
    margin-top: 10px;
    background: #fff;
    padding: 32px 16px;
  }
  ::v-deep .el-pagination {
    text-align: left !important;
  }
  ::v-deep .el-form-item__label {
    text-align: left !important;
  }
</style>
